<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions"
              @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan"
              collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.name" placeholder="类目名称" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.brandId" placeholder="品牌编号" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.level" placeholder="类目层级" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.seoDescription" placeholder="SEO描述" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.seoTitle" placeholder="SEO标题" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.status" placeholder="状态">
              <el-option v-for="item in query.statusOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>

    <div class="block">
      <el-table v-loading="listLoading" :data="list" row-key="id" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
    
        <el-table-column label="类目名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="类目图片" width="110">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.image"></el-image>
          </template>
        </el-table-column>

        <el-table-column label="品牌编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.brandId }}
          </template>
        </el-table-column>
        <el-table-column label="类目层级" width="110">
          <template slot-scope="scope">
            {{ scope.row.level }}
          </template>
        </el-table-column>
        <el-table-column label="SEO描述" width="110">
          <template slot-scope="scope">
            {{ scope.row.seoDescription }}
          </template>
        </el-table-column>
        <el-table-column label="SEO标题" width="110">
          <template slot-scope="scope">
            {{ scope.row.seoTitle }}
          </template>
        </el-table-column>
       
        <el-table-column label="状态" width="110">
          <template slot-scope="scope">
            {{ scope.row.status }}
          </template>
        </el-table-column>

        <el-table-column label="所属租户" width="110">
          <template slot-scope="scope">
            {{ scope.row.tenantId }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column  fixed="right" align="center" prop="created_at" label="操作" width="200">
          <template slot-scope="scope">

            <el-link v-has="'FRONT_GOODS_TYPE_EDIT'" icon="el-icon-edit" type="warning" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              修改
            </el-link>
            <el-link v-has="'FRONT_GOODS_TYPE_REMOVE'" class="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link  v-has="'FRONT_GOODS_TYPE_BIND_BG_GOODSTYPE'"  type="warning" icon="el-icon-edit" size="mini"
              @click="handleBindBGGoodsType(scope.$index, scope.row)">绑定后台类目</el-link>

            <el-link  v-has="'FRONT_GOODS_TYPE_ADD_SUB_NODE'"  type="success" icon="el-icon-edit" size="mini"
              @click="handleEditSubNode(scope.$index, scope.row)">添加下级类目</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="frontGoodsTypeRules" ref="frontGoodsTypeForm">
          <el-form-item v-if="addForVisible" label="编号" required prop="id">
            <el-input v-model="form.id" placeholder="编号" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户"  required prop="tenantId" >
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenant(form)" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织" required prop="organId">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm(form)" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="类目名称" required prop="name">
            <el-input v-model="form.name" placeholder="类目名称" auto-complete="off" />
          </el-form-item>
           
          <el-form-item required  prop="image" label="类目图片">
            <el-upload class="upload-demo" action="/api/file.allService/admin/FileService/uploadFile" :headers="uploadHeader" :with-credentials="true" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :data='fileUloadParams' :on-success="uploadFileOnSuccess" name="file" :limit="1" :on-exceed="handleExceed" :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="类目层级" required prop="level">
            <el-input v-model="form.level" placeholder="类目层级" auto-complete="off" />
          </el-form-item>
          <el-form-item label="品牌编号" required prop="brandId">
            <el-input v-model="form.brandId" placeholder="品牌编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="父节点编号" required prop="parentId">
            <el-input v-model="form.parentId" placeholder="父节点编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="SEO描述" required prop="seoDescription">
            <el-input v-model="form.seoDescription" placeholder="SEO描述" auto-complete="off" />
          </el-form-item>
          <el-form-item label="SEO标题" required prop="seoTitle">
            <el-input v-model="form.seoTitle" placeholder="SEO标题" auto-complete="off" />
          </el-form-item>
          <el-form-item label="排序" required prop="sorted">
            <el-input v-model="form.sorted" placeholder="排序" auto-complete="off" />
          </el-form-item>
          <el-form-item label="状态" required prop="status">
            <el-select v-model="form.status" placeholder="状态">
              <el-option v-for="item in query.statusOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
         
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="block">
      <el-drawer title="绑定后台商品类型" size="85%" :visible.sync="drawerForBindBgGoodsTypsVisible" :direction="direction" :before-close="handleClose">

        <div class="app-container">
          <div class="Search">
          <!--工具条-->
          <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="query">
              <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
                <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions"
                  @change="selectTenant" clearable collapse-tags filterable></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan"
                  collapse-tags clearable filterable></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-input v-model="query.params.name" placeholder="类目名称" />
              </el-form-item>
              <el-form-item>
                <el-select v-model="query.params.status" placeholder="是否为主类目">
                  <el-option v-for="item in query.statusOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryFnBgGoodsType">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="success" icon="el-icon-plus" size="mini" @click="handleQueryBgGoodsType">绑定更多后台类目</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </div>

        <div class="block">
          <el-table v-loading="listLoading" :data="fnBgGoodsTypeRelateList" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column align="center" label="序号" width="45">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="前台类目" width="110">
              <template slot-scope="scope">
                {{ scope.row.frontGoodsTypeName }}
              </template>
            </el-table-column>
            <el-table-column label="后台类目（商品类型）" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsTypeName }}
              </template>
            </el-table-column>
            <el-table-column label="1:主类目，2:非主类上目" width="110">
              <template slot-scope="scope">
                {{ scope.row.mainGoodsType }}
              </template>
            </el-table-column>
            <el-table-column label="组织编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.organId }}
              </template>
            </el-table-column>
            <el-table-column label="排序" width="110">
              <template slot-scope="scope">
                {{ scope.row.sorted }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="110">
              <template slot-scope="scope">
                {{ scope.row.status }}
              </template>
            </el-table-column>
            <el-table-column label="所属租户" width="110">
              <template slot-scope="scope">
                {{ scope.row.tenantId }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="110">
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
            <el-table-column fixed="right"  align="center" prop="created_at" label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-search" size="mini"
                  @click="handleEditFnBgGoodsTypeRelate(scope.$index, scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-plus" size="mini"
                  @click="handleDeleteFnBgGoodsTypeRelate(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="block">
          <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
        </div>
        </el-drawer>
      </div>

      <div class="block">
        <!--弹框-->
        <el-dialog :title="'选取商品类型绑定'" :visible.sync="dialogBindBgGoodsTypeVisible">
          <el-tree
          ref="bgGoodsTypeTree"
          :data="goodsTypeTreeOption"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="goodsTypeTreeProps">
          </el-tree>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogBindBgGoodsTypeVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleCreateBindBgGoodsTypeRelate">确 定</el-button>
          </div>
        </el-dialog>
      </div>



    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFnBgGoodsTypeEditVisible">
        <el-form :model="fnBgGoodsTypeRelate" :rules="frontBackgroundGoodsTypeRelateRules" ref="frontBackgroundGoodsTypeRelateForm">
          <el-form-item  label="主键" required prop="id">
            <el-input v-model="fnBgGoodsTypeRelate.id" placeholder="主键" auto-complete="off" />
          </el-form-item>
          <el-form-item label="拓展字段" required prop="features">
            <el-input v-model="fnBgGoodsTypeRelate.features" placeholder="拓展字段" auto-complete="off" />
          </el-form-item>
          <el-form-item label="前台类目" required prop="frontGoodsTypeId">
            <el-input v-model="fnBgGoodsTypeRelate.frontGoodsTypeId" placeholder="前台类目" auto-complete="off" />
          </el-form-item>
          <el-form-item label="后台类目（商品类型）" required prop="goodsTypeId">
            <el-cascader v-model="fnBgGoodsTypeRelate.goodsTypeId" ref="goodsTypeTreeForm" style="width:100%" placeholder="后台类目（商品类型）" :props="goodsTypeTreeProps" :options="goodsTypeTreeOption" @change="getGoodsType(fnBgGoodsTypeRelate)" collapse-tags filterable></el-cascader>
          </el-form-item>

          <el-form-item label="1:主类目，2:非主类上目" required prop="mainGoodsType">
            <el-select v-model="fnBgGoodsTypeRelate.mainGoodsType" placeholder="1:主类目，2:非主类上目">
              <el-option v-for="item in query.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组织编号" required prop="organId">
            <el-input v-model="fnBgGoodsTypeRelate.organId" placeholder="组织编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="组织路径" required prop="organPath">
            <el-input v-model="fnBgGoodsTypeRelate.organPath" placeholder="组织路径" auto-complete="off" />
          </el-form-item>
          <el-form-item label="父节点编号" required prop="parentId">
            <el-input v-model="fnBgGoodsTypeRelate.parentId" placeholder="父节点编号" auto-complete="off" />
          </el-form-item>
         
          <el-form-item label="排序" required prop="sorted">
            <el-select v-model="fnBgGoodsTypeRelate.sorted" placeholder="排序">
              <el-option v-for="item in query.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" required prop="status">
            <el-select v-model="fnBgGoodsTypeRelate.status" placeholder="状态">
              <el-option v-for="item in query.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属租户" required prop="tenantId">
            <el-input v-model="fnBgGoodsTypeRelate.tenantId" placeholder="所属租户" auto-complete="off" />
          </el-form-item>
          <el-form-item label="备注" required prop="remark">
            <el-input v-model="fnBgGoodsTypeRelate.remark" placeholder="" auto-complete="off" />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFnBgGoodsTypeEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveFnBgGoodsTypeRelate">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>


</template>

<script>
import { getList, queryForList, doDelete, doEdit } from '@/api/FrontGoodsType'
import { getList as queryFnBgGoodsType, doEdit as doEditFnBgGoodsTypeRelate, doDelete as doDeleteFnBgGoodsTypeRelate, batchSave as batchSaveFnBgGoodsTypeRelate } from '@/api/FrontBackgroundGoodsTypeRelate'
import { getList as getOrganPager, querySubordinateOrgan, queryAssigneeOrgan } from '@/api/Organ'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode,getCurrentTimeYYYY_MM_dd_HH_mm_ss } from '@/api/utils'
import { getTenantList, getToken,  getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import { getGoodsTypeTree } from '@/api/GoodsType/'

import localStorageUtil from '@/utils/localStorageUtil'
import sessionStorageUtil from '@/utils/sessionStorageUtil'
export default {
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      drawerForBindBgGoodsTypsVisible: false,
      dialogBindBgGoodsTypeVisible: false,
      dialogFnBgGoodsTypeEditVisible: false,
      direction: 'rtl',
      fileUloadParams: { organId: 1, createBy: 1 },
      fileList: [],
      fnBgGoodsTypeRelateList:[],
      form: {
        brandId: '',
        coditions: '',
        createBy: '',
        createDate: '',
        features: '',
        id: '',
        image: '',
        isDeleted: '',
        level: '',
        name: '',
        organId: '',
        organPath: '',
        parentId: '',
        properties: '',
        remark: '',
        seoDescription: '',
        seoTitle: '',
        sorted: '',
        status: '',
        tenantId: '',
        updateBy: '',
        updateDate: ''
      },
      fnBgGoodsTypeRelate:{
        createBy: '',
        createDate: '',
        features: '',
        frontGoodsTypeId: '',
        goodsTypeId: '',        
        frontGoodsTypeFullName: '',
        goodsTypeFullName: '',
        frontGoodsTypeName: '',
        goodsTypeName: '',
        id: '',
        isDeleted: '',
        mainGoodsType: '',
        organId: '',
        organPath: '',
        parentId: '',
        remark: '',
        sorted: '',
        status: '',
        tenantId: '',
        updateBy: '',
        updateDate: '',
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      frontGoodsTypeRules: {
        name:[{ required: true, message: '请填写类目名称', trigger: 'blur' }],
        organId:[{ required: true, message: '请选择所属组织', trigger: 'blur' }],
        parentId:[{ required: true, message: '请选择父节点', trigger: 'blur' }],
        brandId:[{ required: true, message: '请输入品牌信息', trigger: 'blur' }],
        tenantId:[{ required: true, message: '请选择所属租户', trigger: 'blur' }],
        image:[{ required: true, message: '请上传类目图片', trigger: 'blur' }],
        seoDescription: [{ required: true, message: 'SEO描述不能为空', trigger: 'blur' }],
        seoTitle: [{ required: true, message: 'SEO标题不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '类目层级不能为空', trigger: 'blur' }]
      },
      frontBackgroundGoodsTypeRelateRules: {
        goodsTypeName:[{ required: true, message: '请填写类目名称', trigger: 'blur' }],
        frontGoodsTypeName:[{ required: true, message: '请填写前台类目名称', trigger: 'blur' }],
        organId:[{ required: true, message: '请选择所属组织', trigger: 'blur' }],
        parentId:[{ required: true, message: '请选择父节点', trigger: 'blur' }],
        brandId:[{ required: true, message: '请输入品牌信息', trigger: 'blur' }],
        tenantId:[{ required: true, message: '请选择所属租户', trigger: 'blur' }],
        image:[{ required: true, message: '请上传类目图片', trigger: 'blur' }],
        seoDescription: [{ required: true, message: 'SEO描述不能为空', trigger: 'blur' }],
        seoTitle: [{ required: true, message: 'SEO标题不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '类目层级不能为空', trigger: 'blur' }]
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      goodsTypeTreeProps: { // 配置项（必选）
        value: 'id',
        label: 'typeName',
        children: 'children',
        checkStrictly: true,
        title: '商品类型'
        // disabled:true
      },
      organFormOptions:  [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      tenantOptions:  [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      supplierOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      organQueryModel: 'selfAndSub',
      supplier: null, //供应商
      goodsType: null, //商品分类
      // // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      goodsTypeTreeOption: [],
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          brandId: '', //品牌编号,
          coditions: '', //条件,
          createBy: '', //生成者,
          createDate: '', //生成日期,
          features: '', //拓展字段,
          id: '', //编号,
          image: '', //类目图片,
          isDeleted: '', //删除标识,
          level: '', //类目层级,
          name: '', //类目名称,
          organId: '', //所属组织,
          organPath: '', //组织路径,
          parentId: '', //父节点编号,
          properties: '', //可选属性,
          remark: '', //备注,
          seoDescription: '', //SEO描述,
          seoTitle: '', //SEO标题,
          status: '', //状态：1.上架，0下架,
          tenantId: '', //所属租户,
          updateBy: '', //更新者,
          updateDate: '', //更新日期,

        },
        fnBgGoodsTypeRelate:{
          createBy: '', //生成者,
          createDate: '', //生成日期,
          features: '', //拓展字段,
          frontGoodsTypeId: '', //前台类目,
          goodsTypeId: '', //后台类目（商品类型）,
          isDeleted: '', //删除标识,
          mainGoodsType: '', //1:主类目，2:非主类上目,
          organId: '', //组织编号,
          organPath: '', //组织路径,
          parentId: '', //父节点编号,
          remark: '', //,
          sorted: '', //排序,
          status: '', //状态,
          tenantId: '', //所属租户,
          updateBy: '', //更新者,
          updateDate: '', //更新日期,
          total: 5,
          currentPage: 1,
          pageSize: 10
        },
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }],
        statusOptions:[],
        value: ''
      }
    }
  },
  created() {
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.handleBuildStatusOptions()
    this.initGoodsTypeTree()
    this.fetchData()
  },
  computed:{
    uploadHeader() {
      return {
          'Authorization' : getToken(),
          'OrganId': getOrganId(),
          'tenantId': getTenantId(),
          'userId': getCurrentLoginUserId()
      }
    }
  },
  methods: {
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        } else {
          this.query.params.organId = getOrganId()
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        } else {
          this.query.params.organId = getOrganId()
        }
      }
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage =  this.currentPage || 1
      this.pageSize =  this.pageSize || 10 
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = handleBuildTreeDataStruct(data.entities, 'id', 'parentId') 
        this.listLoading = false
      })
    },

    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.brandId = ''
      this.form.coditions = ''
      this.form.createBy = getCurrentLoginUserId()
      this.form.createDate = getCurrentTimeYYYY_MM_dd_HH_mm_ss()
      this.form.features = '{}'
      this.form.id = ''
      this.form.image = ''
      this.form.isDeleted = ''
      this.form.level = ''
      this.form.name = ''
      this.form.organId = getOrganId()
      this.form.organPath = getOrganPath()
      this.form.parentId = ''
      this.form.properties = '{}'
      this.form.remark = ''
      this.form.seoDescription = ''
      this.form.seoTitle = ''
      this.form.sorted = ''
      this.form.status = ''
      this.form.tenantId = getTenantId()
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)
      this.form.brandId = row.brandId
      this.form.coditions = row.coditions
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.features = row.features
      this.form.id = row.id
      this.form.image = row.image
      this.form.isDeleted = row.isDeleted
      this.form.level = row.level
      this.form.name = row.name
      this.form.organId = row.organId || getOrganId()
      this.form.organPath = row.organPath || getOrganPath()
      this.form.parentId = row.parentId
      this.form.properties = row.properties
      this.form.remark = row.remark
      this.form.seoDescription = row.seoDescription
      this.form.seoTitle = row.seoTitle
      this.form.sorted = row.sorted
      this.form.status = row.status
      this.form.tenantId = row.tenantId || getTenantId()
      this.form.updateBy = row.updateBy ||  getCurrentLoginUserId()
      this.form.updateDate = row.updateDate || getCurrentTimeYYYY_MM_dd_HH_mm_ss()
      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleEditSubNode(index, row){
      this.handleEdit(index, row);
      this.form.parentId = row.id
      this.form.id = ''
      this.addForVisible = false

    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.successful) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {
      this.$refs['frontGoodsTypeForm'].validate((valid) => {
        if (valid) {
          doEdit(this.form).then(response => {
            const data = response.data
            if (data.successful) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData();
              this.dialogFormVisible = false
            } else {
              this.$message({
                  type: 'info',
                  message: data.description || getSystemErrorCode(data.status)
                })
            }
            this.listLoading = false
          })
        } else {
            console.log('error submit!!');
            return false;
          }
      });
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function (item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function () {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(form) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      form.tenantId = null
      let that = this
      debugger
      if (nodesInfo.length) {
        form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(form) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        form.organPath = nodesInfo[0].data.organPath
        form.organId = nodesInfo[0].data.id
        form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function (item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleBuildStatusOptions() {
      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "BizEntity" && item.parentId != '0';
      })
      let statusOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        statusOptions.push(option)
      }
      this.query.statusOptions = statusOptions
    },
    handleBindBGGoodsType(index, row) {
      this.drawerForBindBgGoodsTypsVisible = true
      this.query.fnBgGoodsTypeRelate.frontGoodsTypeId = row.id
      this.query.fnBgGoodsTypeRelate.organId = row.organId
      this.query.fnBgGoodsTypeRelate.tenantId = row.tenantId
      this.query.fnBgGoodsTypeRelate.organPath = row.organPath
      this.form.name = row.name
      this.handleQueryFnBgGoodsType()
    },
    handleQueryFnBgGoodsType(){
      this.query.fnBgGoodsTypeRelate.organId = this.query.fnBgGoodsTypeRelate.organId || getOrganId()
      this.query.fnBgGoodsTypeRelate.organPath = this.query.fnBgGoodsTypeRelate.organPath || getOrganPath()
      this.query.fnBgGoodsTypeRelate.tenantId = this.query.fnBgGoodsTypeRelate.tenantId || getTenantId()
      this.query.fnBgGoodsTypeRelate.currentPage = this.query.fnBgGoodsTypeRelate.currentPage || 1
      this.query.fnBgGoodsTypeRelate.pageSize = this.query.fnBgGoodsTypeRelate.pageSize || 10
      queryFnBgGoodsType(this.query.fnBgGoodsTypeRelate,
      this.query.fnBgGoodsTypeRelate.currentPage, 
      this.query.fnBgGoodsTypeRelate.pageSize).then(response => {

        const data = response.data
        this.query.fnBgGoodsTypeRelate.total = data.totalCount
        this.query.fnBgGoodsTypeRelate.pageSize = data.pageSize
        this.query.fnBgGoodsTypeRelate.currentPage = data.currentPage
        this.fnBgGoodsTypeRelateList = data.entities
        this.listLoading = false

      })
    },
    handleQueryBgGoodsType(){
      this.dialogBindBgGoodsTypeVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    uploadFileOnSuccess(response, file, fileList) {
      if(!response.data.successful){
        this.$message({
          type: 'warning',
          message: response.description
        })
        return;
      }
      this.form.image = response.data.data.fileUrl
    },
    initGoodsTypeTree() {
      this.listLoading = true
      getGoodsTypeTree({ organId: getOrganId(), tenantId: getTenantId() }).then(response => {
        const data = response.data.data
        this.goodsTypeTreeOption = handleBuildTreeDataStruct(data, 'id', 'parentId')
        this.listLoading = false
      })
    },
    handleCreateBindBgGoodsTypeRelate(){
      let leafOnly = true, includeHalfChecked = false
      let goodsTypes = this.$refs.bgGoodsTypeTree.getCheckedNodes(leafOnly, includeHalfChecked)
      this.handleCreateFnBgGoodsTypeRelate(goodsTypes)
    },
    handleCreateFnBgGoodsTypeRelate(goodsTypes){
      if(!(goodsTypes && goodsTypes.length)) {
        this.$message({
          type: 'warning',
          message: "请选择商品类型!"
        })
      }
      let fnBgGoodsTypeRelates = []
      for(let i = 0; i < goodsTypes.length; i++) {
        let fnBgGoodsTypeRelate = {
          createBy: getCurrentLoginUserId(), //生成者,
          createDate: getCurrentTimeYYYY_MM_dd_HH_mm_ss(), //生成日期,
          features: '{}', //拓展字段,
          frontGoodsTypeName: this.form.name,
          frontGoodsTypeId:  this.query.fnBgGoodsTypeRelate.frontGoodsTypeId, //前台类目,
          goodsTypeId: goodsTypes[i].id, //后台类目（商品类型）,
          goodsTypeName: goodsTypes[i].typeName,
          mainGoodsType: '2', //1:主类目，2:非主类上目,
          organId: this.query.fnBgGoodsTypeRelate.organId || getOrganId(), //组织编号,
          organPath: this.query.fnBgGoodsTypeRelate.organPath || getOrganPath(), //组织路径,
          parentId: '1', //父节点编号,
          remark: '1', //,
          sorted: '1', //排序,
          status: '1', //状态,
          tenantId: this.query.fnBgGoodsTypeRelate.tenantId || getTenantId(), //所属租户,
          updateBy: getCurrentLoginUserId(), //更新者,
          updateDate: '' //更新日期,
        }
        fnBgGoodsTypeRelates.push(fnBgGoodsTypeRelate)
      }
      batchSaveFnBgGoodsTypeRelate({entities:fnBgGoodsTypeRelates}).then(response => {
        const data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleQueryFnBgGoodsType()
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
      })
    },
    handleEditFnBgGoodsTypeRelate(index, row){
      this.dialogFnBgGoodsTypeEditVisible = true
        this.fnBgGoodsTypeRelate.createBy = row.createBy
        this.fnBgGoodsTypeRelate.createDate = row.createDate
        this.fnBgGoodsTypeRelate.features= row.features
        this.fnBgGoodsTypeRelate.frontGoodsTypeName = this.form.name
        this.fnBgGoodsTypeRelate.frontGoodsTypeId= row.frontGoodsTypeId
        this.fnBgGoodsTypeRelate.goodsTypeId = row.goodsTypeId
        this.fnBgGoodsTypeRelate.id = row.id
        this.fnBgGoodsTypeRelate.isDeleted = row.isDeleted
        this.fnBgGoodsTypeRelate.mainGoodsType = row.mainGoodsType
        this.fnBgGoodsTypeRelate.organId = row.organId || getOrganId()
        this.fnBgGoodsTypeRelate.organPath = row.organPath || getOrganPath()
        this.fnBgGoodsTypeRelate.parentId = row.parentId
        this.fnBgGoodsTypeRelate.remark = row.remark
        this.fnBgGoodsTypeRelate.sorted = row.sorted
        this.fnBgGoodsTypeRelate.status = row.status
        this.fnBgGoodsTypeRelate.tenantId = row.tenantId || getTenantId()
        this.fnBgGoodsTypeRelate.updateBy = row.updateBy || getCurrentLoginUserId()
        this.fnBgGoodsTypeRelate.updateDate = row.updateDate || getCurrentTimeYYYY_MM_dd_HH_mm_ss()
    },
    handleSaveFnBgGoodsTypeRelate(){

      doEditFnBgGoodsTypeRelate(this.fnBgGoodsTypeRelate).then(response => {
        let data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleQueryFnBgGoodsType()
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
      });
    },
    handleDeleteFnBgGoodsTypeRelate(index, row){

      doDeleteFnBgGoodsTypeRelate(row).then(response => {
        let data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleQueryFnBgGoodsType()
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
      });
    },
    getGoodsType(form) {
      debugger
      let nodesInfo = this.$refs['goodsTypeTreeForm'].getCheckedNodes()
      form.goodsTypeId = nodesInfo[0].data.id
      form.goodsTypePath = nodesInfo[0].data.typePath
      form['goodsTypeName'] = nodesInfo[0].data.typeName
    },
    handleClose(done) {
      this.$confirm('确认关闭绑定后台商品类型操作吗？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
  }
  
}
</script>
